package com.sprite.framework.start.util;

import com.sprite.framework.context.ContextEnvironment;

import java.util.LinkedList;
import java.util.List;

/**
 * 模板字符串
 * 例子：“${user.dir}你好啊”
 * @author LuMengwei
 *
 */
public class Tpl {

	private String orginalValue;
	private String value;
	
	public Tpl(String orginalValue) {
		this.orginalValue = orginalValue;
	}
	
	public String getValue() {
		List<String> pties = new LinkedList<>();
		StringBuilder key = new StringBuilder();
		boolean haskey = false;
		
		for(int i=0; i< orginalValue.length(); i++) {
			char ch = orginalValue.charAt(i);
			if(haskey && ch !='}') {
				key.append(ch);
			}else if('$' == ch && (i+1) != orginalValue.length() && '{'== orginalValue.charAt(i+1)) {
				i++;
				haskey= true;
			}
			
			if(haskey && ch=='}') {
				haskey = false;
				pties.add(key.toString());
			}
		}
		
		value = orginalValue;
		for(String pty : pties) {
			value = value.replace("${"+pty+"}", ContextEnvironment.getProperty(pty));
		}
		
		return value;
	}
}
